

import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.rmi.PortableRemoteObject;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import sessionbeans.PersonalInformationBeanRemote;

/**
 * Servlet implementation class UpdateInformationServlet
 */
public class UpdateInformationServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    private String[] parameterNames = {"password","name","surname","e-mail","address","town"};   
	
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UpdateInformationServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
	}
 
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String[] parameters = new String[parameterNames.length];
		String[] newAbilities = request.getParameterValues("newabilities");
		String updateResult;
		String userId = (String) request.getSession().getAttribute("userId");
		List<String> abilitiesList = new LinkedList<String>();
		InitialContext context;
		PersonalInformationBeanRemote infoBean;
		
		for (int i = 0; i < parameterNames.length; i++) {
			parameters[i] = request.getParameter(parameterNames[i]);
			if (parameters[i] == null) {
				parameters[i] = "";
			}
		}
		
		try {
			context = new InitialContext();
			Object ref = context.lookup("PersonalInformationBeanRemote");
			infoBean = (PersonalInformationBeanRemote)PortableRemoteObject.narrow(ref, PersonalInformationBeanRemote.class);
			
			if (newAbilities != null) {
				for (String s: newAbilities) {
					abilitiesList.add(s);
				}
			}
			updateResult = infoBean.updatePersonalInformation(userId,parameters[0],parameters[1],parameters[2],parameters[3],parameters[4],parameters[5],abilitiesList);
			request.getSession().setAttribute("updateresult",updateResult);
			request.getSession().setAttribute("redirected","UpdatePersonalInformation.jsp");
			response.sendRedirect("PersonalServlet");
		} catch (NamingException e) {
			System.out.println("Naming Exception");
			e.printStackTrace();
		}
	}

}
